package com.wnnight.wys.web.repairs;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wnnight.wys.entity.PageBean;
import com.wnnight.wys.entity.config.PropertyStaff;
import com.wnnight.wys.entity.lanlord.Landlord;
import com.wnnight.wys.entity.repairs.RepairsRecord;
import com.wnnight.wys.excelHandler.RepairsRecordHandler;
import com.wnnight.wys.security.JwtUtils;
import com.wnnight.wys.service.config.PropertyStaffService;
import com.wnnight.wys.service.lanlord.LanlordService;
import com.wnnight.wys.service.repairs.RepairsRecordService;
import com.wnnight.wys.util.repairs.RepairsUtil;
import com.wnnight.wys.vo.AppraiseVo;
import com.wnnight.wys.vo.MaintenanceVo;
import com.wnnight.wys.vo.RepairsRecordVo;
import com.wnnight.wys.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author rzh6230
 * 2022/8/28 11:25
 */
@RestController
@RequestMapping("/api/v1/bx/record")
public class RepairsRecordController {
    @Autowired
    private RepairsRecordService repairsRecordService;

    @Resource
    private PropertyStaffService propertyStaffService;

    @Autowired
    private LanlordService lanlordService;

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('bx:record:list')")
    public ResultVo<?> list(@RequestBody @Validated RepairsRecordVo repairsRecordVo, HttpServletRequest request) {
        QueryWrapper<RepairsRecord> wrapper = new QueryWrapper<>();
        String jwt = request.getHeader("jwt");
        int personId = (int) JwtUtils.getInfo(jwt, "id");
        int roleId = (int) JwtUtils.getInfo(jwt, "roleId");
        wrapper.like(!"".equals(repairsRecordVo.getRepNumWord()), "rep_num", repairsRecordVo.getRepNumWord());
        wrapper.like(!"".equals(repairsRecordVo.getPersonWord()), "person", repairsRecordVo.getPersonWord());
        wrapper.like(!"".equals(repairsRecordVo.getMtWord()), "maintenance", repairsRecordVo.getMtWord());
        wrapper.eq(!"".equals(repairsRecordVo.getRepStatus()), "rep_status", repairsRecordVo.getRepStatus());
        wrapper.ge(!"".equals(repairsRecordVo.getStartTime()), "rep_time", repairsRecordVo.getStartTime());
        wrapper.le(!"".equals(repairsRecordVo.getEndTime()), "rep_time", repairsRecordVo.getEndTime());
        wrapper.orderBy(true, false, "rep_time");
        if (6 != roleId) {
            wrapper.eq("person_id", personId);
            wrapper.eq("person_type", 0);
        }
        PageBean<List<RepairsRecord>> pageBean = repairsRecordVo.getPageBean();
        IPage<RepairsRecord> page = repairsRecordService.page(new Page<>(pageBean.getCurrPage(), pageBean.getPageSize()), wrapper);
        pageBean.setData(page.getRecords());
        pageBean.setTotalPages((int) page.getPages());
        pageBean.setTotalNum((int) page.getTotal());

        return new ResultVo<>(pageBean);
    }

    @PostMapping("/add")
    @PreAuthorize("hasAuthority('bx:record:add')")
    @Transactional
    public ResultVo<?> add(@RequestBody @Validated RepairsRecord repairsRecord, HttpServletRequest request) {
        String jwt = request.getHeader("jwt");
        int personId = (int) JwtUtils.getInfo(jwt, "id");
        int roleId = (int) JwtUtils.getInfo(jwt, "roleId");
        repairsRecord.setPersonId(personId);
        repairsRecord.setPersonType("1");
        PropertyStaff propertyStaff = propertyStaffService.getStaffByPlaceId(repairsRecord.getRepPlaceIds()[1]);
        if (propertyStaff != null) {
            repairsRecord.setSendPerson(propertyStaff.getName());
            repairsRecord.setSpPhone(propertyStaff.getPhone());
        } else {
            repairsRecord.setSendPerson("彭于晏");
            repairsRecord.setSpPhone("18215755261");
        }
        if (roleId == 7) {
            Landlord landlord = lanlordService.getById(personId);
            repairsRecord.setPerson(landlord.getName());
            repairsRecord.setPePhone(landlord.getPhone());
            repairsRecord.setPersonType("0");
        } else {
            PropertyStaff propertyStaff1 = propertyStaffService.getById(personId);
            repairsRecord.setPerson(propertyStaff1.getName());
            repairsRecord.setPePhone(propertyStaff1.getPhone());
            repairsRecord.setPersonType("1");
        }
        repairsRecord.setRepNum(RepairsUtil.getRecordNum());
        repairsRecord.setRepTime(DateUtil.now());
        repairsRecord.setRepStatus("1");
        System.out.println(repairsRecord);
        repairsRecordService.save(repairsRecord);
        return ResultVo.SUCCESS;
    }

    /**
     * 业主评价维修
     *
     * @param appraiseVo 参数
     * @return 成功状态码
     */
    @PostMapping("/update/appraise")
    @PreAuthorize("hasAuthority('bx:record:appraise')")
    public ResultVo<?> updateAppraise(@RequestBody @Validated AppraiseVo appraiseVo) {
        RepairsRecord repairsRecord = new RepairsRecord();
        repairsRecord.setId(appraiseVo.getRepairsId());
        repairsRecord.setRepAppraise(appraiseVo.getAppraise());
        repairsRecord.setRepScore(appraiseVo.getScore());
        repairsRecord.setRepStatus("3");
        repairsRecordService.updateById(repairsRecord);
        return ResultVo.SUCCESS;
    }


    @PostMapping("/update/maintenance")
    @PreAuthorize("hasAuthority('bx:record:maintenance')")
    public ResultVo<?> update(@RequestBody @Validated MaintenanceVo maintenanceVo) {
        RepairsRecord repairsRecord = new RepairsRecord();
        repairsRecord.setId(maintenanceVo.getRepairsId());
        repairsRecord.setMaintenance(maintenanceVo.getMaintenance());
        repairsRecord.setMtPhone(maintenanceVo.getMtPhone());
        repairsRecord.setRepStatus("2");
        repairsRecordService.updateById(repairsRecord);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/update/cancel")
    @PreAuthorize("hasAuthority('bx:record:cancel')")
    public ResultVo<?> cancel(int repairsId) {
        RepairsRecord repairsRecord = new RepairsRecord();
        repairsRecord.setId(repairsId);
        repairsRecord.setRepStatus("4");
        repairsRecordService.updateById(repairsRecord);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/update/complete")
    @PreAuthorize("hasAuthority('bx:record:complete')")
    public ResultVo<?> complete(int repairsId) {
        RepairsRecord repairsRecord = new RepairsRecord();
        repairsRecord.setId(repairsId);
        repairsRecord.setRepStatus("5");
        repairsRecordService.updateById(repairsRecord);
        return ResultVo.SUCCESS;
    }

    @PostMapping("/repairsInfo")
    @PreAuthorize("hasAuthority('bx:record:info')")
    public ResultVo<?> repairsInfo() {
        return new ResultVo<>(repairsRecordService.getRepairsInfo());
    }

    @PostMapping("/download")
    @PreAuthorize("hasAuthority('bx:record:download')")
    public void download(@RequestBody @Validated RepairsRecordVo repairsRecordVo, HttpServletRequest request, HttpServletResponse response) throws IOException {
        QueryWrapper<RepairsRecord> wrapper = new QueryWrapper<>();
        String jwt = request.getHeader("jwt");
        int personId = (int) JwtUtils.getInfo(jwt, "id");
        int roleId = (int) JwtUtils.getInfo(jwt, "roleId");
        wrapper.like(!"".equals(repairsRecordVo.getRepNumWord()), "rep_num", repairsRecordVo.getRepNumWord());
        wrapper.like(!"".equals(repairsRecordVo.getPersonWord()), "person", repairsRecordVo.getPersonWord());
        wrapper.like(!"".equals(repairsRecordVo.getMtWord()), "maintenance", repairsRecordVo.getMtWord());
        wrapper.eq(!"".equals(repairsRecordVo.getRepStatus()), "rep_status", repairsRecordVo.getRepStatus());
        wrapper.ge(!"".equals(repairsRecordVo.getStartTime()), "rep_time", repairsRecordVo.getStartTime());
        wrapper.le(!"".equals(repairsRecordVo.getEndTime()), "rep_time", repairsRecordVo.getEndTime());
        if (6 != roleId) {
            wrapper.eq("person_id", personId);
            wrapper.eq("person_type", roleId);
        }
        PageBean<List<RepairsRecord>> pageBean = repairsRecordVo.getPageBean();
        IPage<RepairsRecord> page = repairsRecordService.page(new Page<>(pageBean.getCurrPage(), pageBean.getPageSize()), wrapper);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), RepairsRecord.class).registerWriteHandler(new RepairsRecordHandler()).autoCloseStream(Boolean.FALSE).sheet("模板")
                    .doWrite(page.getRecords());
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getWriter(), ResultVo.ERROR);
            response.getWriter().flush();
            response.getWriter().close();
        }
    }
}
